package cn.com.mdx.union.percolation;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;

import java.awt.*;

/**
 * @author huangyuan
 * @date 2020/3/29
 * @description
 */
public class PercolationOptVisualizer {
    // delay in per (controls animation speed)
    private static final int DELAY = 100;

    // draw n-by-n percolation system
    static void draw(Percolation per, int n) {
        StdDraw.clear();
        StdDraw.setPenColor(StdDraw.BLACK);
        StdDraw.setXscale(-0.05 * n, 1.05 * n);
        StdDraw.setYscale(-0.05 * n, 1.05 * n);   // leave a border to write text
        StdDraw.filledSquare(n / 2.0, n / 2.0, n / 2.0);
        // draw n-by-n grid
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= n; col++) {
                if (per.isFull(row , col))
                    StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);
                else if (per.isOpen(row, col))
                    StdDraw.setPenColor(StdDraw.WHITE);
                else
                    StdDraw.setPenColor(StdDraw.BLACK);
                StdDraw.filledSquare(col - 0.5, n - row + 0.5, 0.45);
            }
        }
        // write status text
        StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 12));
        StdDraw.setPenColor(StdDraw.BLACK);
        StdDraw.text(0.25 * n, -0.025 * n, per.getNumOfOpenSite() + " open sites");
        if (per.percolates()) StdDraw.text(0.75 * n, -0.025 * n, "percolates");
        else StdDraw.text(0.75 * n, -0.025 * n, "does not percolate");

    }

    public static void main(String[] args) {
        In in = new In(args[0]);      // input file
        int n = in.readInt();         // n-by-n percolation system
        // turn on animation mode
        StdDraw.enableDoubleBuffering();
        // repeatedly read in sites to open and draw resulting system
        Percolation per = new Percolation(n);
        draw(per, n);
        StdDraw.show();
        StdDraw.pause(DELAY);
        while (!in.isEmpty()) {
            int i = in.readInt();
            int j = in.readInt();
            per.open(i, j);
            draw(per, n);
            StdDraw.show();
            StdDraw.pause(DELAY);
        }
    }
}
